package com.lin.linchatgpt.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.lin.linchatgpt.entity.User;
import com.lin.linchatgpt.entity.dto.LoginDTO;
import com.lin.linchatgpt.entity.dto.RegisterDTO;
import com.lin.linchatgpt.exception.LinException;
import com.lin.linchatgpt.service.UserService;
import com.lin.linchatgpt.service.email.EmailService;
import com.lin.linchatgpt.utils.LinResult;
import com.lin.linchatgpt.utils.ResultCode;
import com.mybatisflex.core.util.StringUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * Copyright(C),2022年-2022,霖霖
 *
 * @author 霖霖
 * @version 1.0
 * @date 2023/4/1 17:03
 * @Description 用户管理
 */
@RestController
@CrossOrigin
@RequestMapping("lin_chat/user")
@Slf4j
@SaCheckLogin
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private EmailService emailService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * @return com.lin.linchatgpt.utils.LinResult
     * @description 用户注册
     * @author 霖霖
     * @date 2023/6/12 22:58
     * @params [com.lin.linchatgpt.entity.User]
     */
    @PostMapping("register")
    public LinResult register(@RequestBody RegisterDTO registerDTO) {
        String validCode = (String) redisTemplate.opsForValue().get(registerDTO.getUuid());

        Optional.ofNullable(validCode).orElseThrow(() -> new LinException(ResultCode.VALID_CODE_EXPIRED, "验证码已过期"));

        if (!validCode.equals(registerDTO.getValidCode())) {
            return LinResult.error().message("验证码错误");
        }
        User user = new User();
        BeanUtils.copyProperties(registerDTO, user);
        if (userService.register(user)) {
            emailService.sendEmail(registerDTO.getEmail());
            return LinResult.success().message("注册成功，请前往邮箱激活账号");
        }
        return LinResult.error().message("注册失败");
    }

    /**
     * @description 用户登录
     * @author 霖霖
     * @date 2023/7/20 16:28
     * @params  [com.lin.linchatgpt.entity.dto.LoginDTO]
     * @return  com.lin.linchatgpt.utils.LinResult
     */
    @PostMapping("login")
    public LinResult userLogin(@RequestBody LoginDTO loginDTO) {
        User userSuccess = userService.login(loginDTO);
        if (userSuccess != null && StringUtil.isNotBlank(userSuccess.getId())) {
            switch (userSuccess.getStatus()) {
                case 0:
                    return LinResult.error().message("账号邮箱未激活").code(ResultCode.UNAUTHENTICATED);
                case 2:
                    return LinResult.error().message("账号已被封禁").code(ResultCode.UNAUTHENTICATED);
                default:
                    break;
            }
            StpUtil.login(userSuccess.getId());
            return LinResult.success().message("登录成功").data("lin-token", StpUtil.getTokenInfo());
        }
        return LinResult.error().message("用户名或密码错误").code(ResultCode.UNAUTHENTICATED);

    }

    /**
     * @return com.lin.linchatgpt.utils.LinResult
     * @description 获取用户信息
     * @author 霖霖
     * @date 2023/6/10 23:13
     * @params [javax.servlet.http.HttpServletRequest]
     */
    @GetMapping("info")
    public LinResult getUserInfo() {
        return LinResult.success().data("item", userService.getById((String) StpUtil.getLoginId()));
    }
    @GetMapping("logout")
    public LinResult logout() {
        StpUtil.logout(StpUtil.getLoginId());
        return LinResult.success().message("退出成功");
    }


}
